/**********************************************************

file:  Timer.c

Author:	  albert

 **********************************************************/
#include "Timer.h"
volatile unsigned char timer_tick = 0;
volatile unsigned char timer_enable = 0;

/**************************************************************************
 *  CTC mode Timer1, use the longest period @14.7456MHZ                   *
 **************************************************************************/
void Timer1_TwoSecond(void)
{
  timer_tick = 0;
  TCCR1B |= (1 << WGM12); // Configure timer 1 for CTC mode 

  TIMSK |= (1 << OCIE1A); // Enable CTC interrupt 

  sei(); //  Enable global interrupts

  //14.745600MHz AVR clock, with a prescaler of 1024 =>14400hz timer1
  //one timer cycle=70us,15 tick=1ms
  OCR1A = 65535; // Set CTC compare value to 1Hz at  

  TCCR1B |= ((1 << CS10) | (1 << CS12)); // Start timer at Fcpu/1024

}

/**************************************************************************
 * Clear the Timer1 interrupt flag                                        *
 **************************************************************************/

void Timer1_clear(void)
{
  TIMSK ^= (1 << OCIE1A); // Enable CTC interrupt
  timer_tick = 0;
  timer_enable = 0;
}

/**************************************************************************
 *                                                                        *
 **************************************************************************/

void Timer1_prescale1024_start(void)
{
  TCCR1B |= ((1 << CS10) | (1 << CS12)); // Start timer at Fcpu/1024
  TCNT1 = 0;
}

/**************************************************************************
 *                                                                        *
 **************************************************************************/

void Timer1_prescale1024_end(void)
{
  TCCR1B |= ((0 << CS10) | (0 << CS12)); // close clk

}

/**************************************************************************
 *                                                                        *
 **************************************************************************/

ISR(TIMER1_COMPA_vect)
{
  //interrupt will automatically clear the flag
  timer_tick = 1;
}
